package com.carkeeper.user.service.impl;

import com.carkeeper.user.config.MD5_SHA_1_Utils;
import com.carkeeper.user.dao.AdminDao;
import com.carkeeper.user.dao.DepartmentMapper;
import com.carkeeper.user.dao.EmployeeMapper;
import com.carkeeper.user.pojo.Department;
import com.carkeeper.user.pojo.Employee;
import com.carkeeper.user.pojo.Role;
import com.carkeeper.user.service.AdminService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName AdminServiceImpl
 * @Description TODO
 * @Author yangbin
 * @Date 2020/11/25 10:58
 * @Version 1.0
 */
@Service
@Transactional
public class AdminServiceImpl implements AdminService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 开户
     * @param employee
     * @param roleId
     * @return
     */
    @Override
    public int updateAdmin(Employee employee, Integer roleId) {
        // 为员工开通用户名和密码,前端已经输入了用户名和密码，现在只需要加密即可
        String username = employee.getUsername();
        String password = employee.getPassword();
        Employee employee1 = employeeMapper.findAdminByUsername(username);
        if (employee1 != null) {
            throw new RuntimeException("该用户已存在");
        }
        // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String salt = BCrypt.gensalt();
        String newPassword = BCrypt.hashpw(password, salt);
        employee.setPassword(newPassword);
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());
        // 为用户授权(将employeeId和roleId存入tb_employee_role表中)
        // 先查询中间表是否有数据，有了先删除，在添加新数据
        List<Integer> list = employeeMapper.findEmployeeAndRole(employee.getId());
        if (list != null && list.size() > 0) {
            employeeMapper.deleteEmployeeAndRole(employee.getId());
        }
        employeeMapper.addEmployeeAndRole(employee.getId(), roleId);
        return employeeMapper.updateByPrimaryKeySelective(employee);
    }

    /**
     * 查询所有
     * @return
     */
    @Override
    public List<Map<String, Object>> findAdminList() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 查询username不为空的所有员工
        List<Employee> adminList = adminDao.findAdminList();
        for (Employee employee : adminList) {
            // 初始化存储用户的Map集合
            Map<String, Object> adminMap = new HashMap<>();
            adminMap.put("id", employee.getId());
            adminMap.put("username", employee.getUsername());
            adminMap.put("name", employee.getName());
            adminMap.put("phone", employee.getPhone());
            adminMap.put("email", employee.getEmail());
            adminMap.put("departmentId", employee.getDepartmentId());
            // 通过用户id查询用户拥有的角色
            List<Role> roleList = employeeMapper.findRoleByEmployeeId(employee.getId());
            // 定义角色字符串

            String roleStr = "";
            for (Role role : roleList) {
                if (roleList.size() > 1) {
                    roleStr += role.getName() + ",";
                    roleStr = roleStr.substring(0, roleStr.length() - 1);
                    adminMap.put("roleName", roleStr);
                } else {
                    adminMap.put("roleName", role.getName());
                }
            }
            adminMap.put("status", employee.getAccountStatus());
            // 将每一条数据添加到list集合
            resultList.add(adminMap);
        }
        return resultList;
    }

    /**
     * 修改状态
     * @param employeeId
     * @return
     */
    @Override
    public int updateStatus(Integer employeeId) {
        Employee employee = employeeMapper.selectByPrimaryKey(employeeId);
        if (employee.getAccountStatus() == 1) {
            employee.setAccountStatus(2);
        } else {
            employee.setAccountStatus(1);
        }
        return employeeMapper.updateByPrimaryKeySelective(employee);
    }

    /**
     * 分页条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Map<String, Object>> findPage(Map<String, Object> searchMap, int page, int size) {
        Example example = createExample(searchMap);
        PageHelper.startPage(page, size);
        List<Employee> employeeList = employeeMapper.selectByExample(example);
        Page<Map<String, Object>> resultList = new Page<>();
        // List<Map<String, Object>> resultList = new ArrayList<>();
        for (Employee employee : employeeList) {
            if (StringUtils.isNotEmpty(employee.getUsername())) {
                // 初始化存储用户的Map集合
                Map<String, Object> adminMap = new HashMap<>();
                adminMap.put("id", employee.getId());
                adminMap.put("username", employee.getUsername());
                adminMap.put("name", employee.getName());
                adminMap.put("phone", employee.getPhone());
                adminMap.put("email", employee.getEmail());
                adminMap.put("departmentId", employee.getDepartmentId());
                // 通过用户id查询用户拥有的角色
                List<Role> roleList = employeeMapper.findRoleByEmployeeId(employee.getId());
                // 定义角色字符串
                String roleStr = "";
                for (Role role : roleList) {
                    roleStr += role.getName() + ",";
                }
                roleStr = roleStr.substring(0, roleStr.length() - 1);
                adminMap.put("roleName", roleStr);
                adminMap.put("status", employee.getAccountStatus());
                // 将每一条数据添加到list集合
                resultList.add(adminMap);
            }
        }
        return  resultList;
    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Employee.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            //用户名
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andEqualTo("username", searchMap.get("username"));
            }
            //部门名称
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andEqualTo("name", searchMap.get("name"));
            }
            //电话号码
            if (searchMap.get("phone") != null && !"".equals(searchMap.get("phone"))) {
                criteria.andEqualTo("phone", searchMap.get("phone"));
            }
            //所属部门
            if (searchMap.get("departmentId") != null && !"".equals(searchMap.get("departmentId"))) {
                criteria.andEqualTo("departmentId", searchMap.get("departmentId"));
            }
            //账号状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andEqualTo("accountStatus", searchMap.get("status"));
            }
        }
        return example;
    }

    /**
     * （测试）
     * @param username
     * @param password
     * @return
     */
    @Override
    public Boolean Login(String username, String password) {
        Employee employee = new Employee();
        employee.setUsername(username);
        Employee selectOne = employeeMapper.selectOne(employee);
        if (selectOne == null) {
            throw new RuntimeException("用户不存在");
        }
        String onePassword = selectOne.getPassword();
        return onePassword.equals(password);
    }

    @Override
    public Employee findById(String username) {
        Employee employee = new Employee();
        employee.setUsername(username);
        return employeeMapper.selectOne(employee);
    }
}
